from typing import List, Optional, Dict, Any
from src import retMes
from sqlalchemy.orm import Session
from src.models import sys_menu as SysMenuModels
from src.schemas.login_manager import AuthManager


# ---------------------- 辅助：把 ORM 对象 → 前端所需字典 ----------------------
def _node_of(menu: SysMenuModels) -> Dict[str, Any]:
    return {
        "index": menu.menu_index,
        "label": menu.label,
        "icon": menu.icon,
        "path": menu.path,
    }


def menu_tree(userName: str,
              db: Session,
              auth: AuthManager) -> dict:
    api_id = auth.api_id

    # 1. 全部启用菜单
    menus = (db.query(SysMenuModels.SysMenu)
             .filter(SysMenuModels.SysMenu.api_id == api_id,
                     SysMenuModels.SysMenu.status == True,
                     SysMenuModels.SysMenu.deletion_mark == False)
             .order_by(SysMenuModels.SysMenu.sort_order)
             .all())

    # 2. 建立两本字典
    id_2_node = {m.id: m for m in menus}  # id → ORM 对象
    grouped: Dict[str, List[Dict[str, Any]]] = {}  # parent_id → 孩子列表

    for m in menus:
        node = _node_of(m)
        # 把 id 也塞进字典，后面递归要用
        node["id"] = m.id
        grouped.setdefault(m.parent_id, []).append(node)

    # 3. 递归挂 children（用当前节点的 id 当 key）
    def attach_children(nodes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        for node in nodes:
            kids = grouped.get(node["id"], [])  # ← 用 id 找孩子
            if kids:
                node["children"] = attach_children(kids)
        return nodes

    # 4. 从根节点（parent_id == "0"）开始
    tree = attach_children(grouped.get("0", []))
    return retMes.Success(tree).mes()


def permission_tree(userName: str,
                    db: Session,
                    auth: AuthManager) -> dict:
    api_id = auth.api_id
    data = [
        {'index': 'User',
         'label': '用户管理',
         'path': 'views/SysSettings/UserMgr',
         'permissions': [
             "demo1:view",
             "Search",
             "add",
             "edit",
             "delete",
             "resetPassword"
         ]

         },
        {'index': 'object',
         'label': '对象定义',
         'path': 'views/SysSettings/object/index',
         'permissions': [
             "demo1:view",
             "Search",
             "add",
             "edit",
             "delete"
         ]

         },
        {'index': 'menu',
         'label': '菜单',
         'path': 'views/SysSettings/Menu',
         'permissions': [
             "demo1:view",
             "Search",
             "add",
             "edit",
             "delete"
         ]

         },
        {'index': 'Dict',
         'label': '数据字典',
         'path': 'views/SysSettings/Dict',
         'permissions': [
             "demo1:view",
             "Search",
             "add",
             "edit",
             "delete",
             "lineAdd",
             "lineedit",
             "linedelete"
         ]

         },
        {'index': 'permissionsInfoOne',
         'label': '权限演示-1',
         'path': 'views/SysSettings/UserInfo',
         'permissions': [
             "demo1:view",
             "demo1:create",
             "demo1:edit",
             "demo1:delete"
         ]

         },
        {'index': 'permissionsInfoTwo',
         'label': '权限演示-2',
         'path': 'views/SysSettings/AccountSetting',
         'permissions': [
             "demo2:view",
             "demo2:create",
             "demo2:edit",
             "demo2:delete"
         ]

         }
    ]
    return retMes.Success(data).mes()
